﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;

public partial class CustomerManagement_CashWithdrawManagementDetail : System.Web.UI.Page
{
    TextBox txtNote;

    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataSet DstDetails
    {
        get
        {
            DataSet dstDetails = null;
            if (ViewState["DstDetails"] != null)
            {
                dstDetails = (DataSet)ViewState["DstDetails"];
            }
            return dstDetails;
        }
        set
        {
            ViewState["DstDetails"] = value;
        }
    }

    private bool IsAudit
    {
        get
        {
            bool isAudit = false;
            if (ViewState["IsAudit"] != null)
            {
                isAudit = Convert.ToBoolean(ViewState["IsAudit"]);
            }
            return isAudit;
        }
        set
        {
            ViewState["IsAudit"] = value;
        }
    }

    private List<Model.CashWithdrawType> CashWithdrawTypes
    {
        get
        {
            List<Model.CashWithdrawType> cashWithdrawTypes = null;
            if (ViewState["CashWithdrawTypes"] != null)
            {
                cashWithdrawTypes = (List<Model.CashWithdrawType>)ViewState["CashWithdrawTypes"];
            }
            return cashWithdrawTypes;
        }
        set
        {
            ViewState["CashWithdrawTypes"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("300400110");
        if (!IsPostBack)
        {
            BindMain();
            BindDetails();
            if (this.IsAudit)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
            }
        }

        Session["FCode"] = "300400110";
    }

    private void BindDropType(DropDownList drop, string typeId)
    {
        for (int i = 0; i < drop.Items.Count; i++)
        {
            if (drop.Items[i].Value == typeId)
            {
                drop.SelectedIndex = i;
                break;
            }
        }
    }

    private void BindDropCashWithdrawTypes(DropDownList drop, string typeId)
    {
        if (this.CashWithdrawTypes == null)
        {
            this.CashWithdrawTypes = new BLL.CashWithdrawType().GetAllList();
        }
        ListItem item;


        for (int i = 0; i < this.CashWithdrawTypes.Count; i++)
        {
            if (this.CashWithdrawTypes[i].Type_Disabled == 0)
            {
                item = new ListItem();
                item.Text = this.CashWithdrawTypes[i].Type_Name;
                item.Value = this.CashWithdrawTypes[i].Type_ID;

                drop.Items.Add(item);
            }
        }

        for (int i = 0; i < drop.Items.Count; i++)
        {
            if (drop.Items[i].Value == typeId)
            {
                drop.SelectedIndex = i;
                break;
            }
        }
    }

    private void BindMain()
    {

        DataSet dst = new BLL.CashWithdrawDoc().GetMainById(this.Code);
        if (dst.Tables[0].Rows.Count > 0)
        {
            this.IsAudit = dst.Tables[0].Rows[0]["Doc_Check"].ToString() == "1" ? true : false;
        }
        dlistMain.DataSource = dst;
        dlistMain.DataBind();

        if (this.IsAudit)
        {
            dlistMain.Enabled = false;
        }
    }

    private void BindDetails()
    {
        this.DstDetails = new BLL.CashWithdrawDocDetails().GetDetailsById(this.Code);
        dlistDetail.DataSource = this.DstDetails;
        dlistDetail.DataBind();
        if (this.IsAudit)
        {
            dlistDetail.Enabled = false;
        }
    }

    protected void btnAddDetail_Click(object sender, EventArgs e)
    {
        try
        {
            string customerCode = hidUserCode.Value;
            SetValueOfDataTable(this.DstDetails);
            if (customerCode != "")
            {
                string[] customersArray = customerCode.Split('|');
                if (customersArray.Length > 0)
                {
                    string[] customer;
                    for (int i = 0; i < customersArray.Length; i++)
                    {
                        customer = customersArray[i].Split(' ');
                        if (customer.Length == 2)
                        {
                            this.DstDetails = new BLL.CashWithdrawDocDetails().AddDataRowToDataTable(this.DstDetails, Convert.ToString(this.DstDetails.Tables[0].Rows.Count + 1), customer[0], customer[1],DateTime.Now);
                        }
                    }
                    dlistDetail.DataSource = this.DstDetails;
                    dlistDetail.DataBind();
                }
            }
            else
            {
                return;//Share.Alert(this.Page, "请选择会员！");
            }
            hidUserCode.Value = "";
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400110", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.CashWithdrawDoc cwd = new BLL.CashWithdrawDoc().GetModel(this.Code);
            if (cwd != null)
            {
                if (cwd.Doc_Check==1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            SetValueOfDataTable(this.DstDetails);
            if (this.DstDetails.Tables[0].Rows.Count == 0)
            {
                throw new Exception("请选择您要调整的会员！");
            }
            if (new BLL.CashWithdrawDoc().Save(this.Code, this.DstDetails, ((TextBox)dlistMain.Items[0].FindControl("txtNote")).Text))
            {
                Share.InsertLog("300400110", "00017");
                Share.Alert(this.Page, "保存成功！");
            }
            else
            {
                Share.Alert(this.Page, "保存失败，请重新尝试保存！");
            }

        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400110", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {

            Model.CashWithdrawDoc cwd = new BLL.CashWithdrawDoc().GetModel(this.Code);
            if (cwd != null)
            {
                if (cwd.Doc_Check == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            DataSet dstDetails = new BLL.CashWithdrawDocDetails().GetDetails(this.Code);
            for (int i = 0; i < dstDetails.Tables[0].Rows.Count; i++)
            {
                if (Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"]) != Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ExpectedWithdrawAmount"]))
                {
                    throw new Exception("帐号为" + dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString() + "的会员,实际提现金额+提现手续费不等于期望提现金额！");
                }
            }

            StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
            StringBuilder strSqlToUpdateErpDB = new StringBuilder();
            string strCommandOfBStyle;
            string strCommandOfErp;
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            string[] strArraySqlCommandArrayToUpdateBStyleDB;
            string[] strArraySqlCommandArrayToUpdateErpDB;
            string operatorId = Share.UserValue(0);
            char[] charToTrim = new char[] { '|' };
            bool result = false;
            string user = Share.UserValue(0);

            for (int i = 0; i < dlistMain.Items.Count; i++)
            {
                txtNote = (TextBox)dlistMain.Items[i].FindControl("txtNote");
            }

            strSqlToUpdateBStyleDB.Append("update CashWithdrawDoc set Doc_Check=1,Doc_Checker='");
            strSqlToUpdateBStyleDB.Append(user);
            strSqlToUpdateBStyleDB.Append("',Doc_CheckDate='");
            strSqlToUpdateBStyleDB.Append(DateTime.Now);
            strSqlToUpdateBStyleDB.Append("',Doc_Description='");
            strSqlToUpdateBStyleDB.Append(txtNote.Text.Trim());
            strSqlToUpdateBStyleDB.Append("' where Doc_ID='");
            strSqlToUpdateBStyleDB.Append(this.Code);
            strSqlToUpdateBStyleDB.Append("'|");

            for (int i = 0; i < dstDetails.Tables[0].Rows.Count; i++)
            {
                if (dstDetails.Tables[0].Rows[i]["DD_Type"].ToString() == "balance")
                {
                    if (Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"]) > Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["BALANCE"]))
                    {
                        throw new Exception("帐号为" + dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString() + "的会员,提现金额大于结余款余额！");
                    }

                    string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString((Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"])) * -1, dstDetails.Tables[0].Rows[i]["VipDM"].ToString());
                    strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                    strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                    string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("009", "", operatorId, operatorId, dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString(), (Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"])) * -1);
                    strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);
                }
                else if (dstDetails.Tables[0].Rows[i]["DD_Type"].ToString() == "margin")
                {
                    if (Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"]) > Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["margin"]))
                    {
                        throw new Exception("帐号为" + dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString() + "的会员提现金额大于保证金余额！");
                    }

                    string strUpdateVipCustomerSqlString = new BLL.V_CUSTOMER_AUTO().BuildUpdateVipCustomerSqlString((Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"])) * -1, dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString());
                    strSqlToUpdateBStyleDB.Append(strUpdateVipCustomerSqlString);

                    string strInsertMarginManagementSqlString = new BLL.MarginAdjust().BuildInsertMarginSqlString(operatorId, operatorId, dstDetails.Tables[0].Rows[i]["DD_CustomerID"].ToString(), (Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_ActualWithdrawAmount"]) + Convert.ToDecimal(dstDetails.Tables[0].Rows[i]["DD_CommissionCharge"])) * -1);
                    strSqlToUpdateBStyleDB.Append(strInsertMarginManagementSqlString);
                }
            }

            if (strSqlToUpdateErpDB.ToString() == "")
            {
                strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
                strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
                result = new SQLServerDAL.ORDERDOC().Deliver(strArraySqlCommandArrayToUpdateBStyleDB);
            }
            else
            {
                strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
                strCommandOfErp = strSqlToUpdateErpDB.ToString();

                strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
                strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);

                LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
            }



            if (result)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
                BindMain();
                BindDetails();

                Share.InsertLog("300400110", "00010");
                Share.Alert(this.Page, "审核成功！");
            }
            else
            {
                Share.Alert(this.Page, "审核失败，请重新审核！");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }

    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400110", "00003"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {

            Model.CashWithdrawDoc cwd = new BLL.CashWithdrawDoc().GetModel(this.Code);
            if (cwd != null)
            {
                if (cwd.Doc_Check == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            bool result = new BLL.CashWithdrawDoc().Delete(Code);
            if (result)
            {
                Share.InsertLog("300400110", "00003");
                Response.Write("<script>alert('删除成功！');window.location.href='CashWithdrawManagement.aspx'</script>");
            }
            else
            {
                Response.Write("<script>alert('删除失败！');</script>");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("CashWithdrawManagementDetail.aspx?code=" + this.Code);
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("CashWithdrawManagement.aspx");
    }

    protected void dlistDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            if (this.DstDetails != null)
            {
                this.DstDetails.Tables[0].Rows.RemoveAt(e.Item.ItemIndex);
                dlistDetail.DataSource = this.DstDetails;
                dlistDetail.DataBind();
            }
        }
    }

    protected void dlistDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            HtmlInputHidden hidType = (HtmlInputHidden)e.Item.FindControl("hidType");
            HtmlInputHidden hidCashWithdrawType = (HtmlInputHidden)e.Item.FindControl("hidCashWithdrawType");
            DropDownList dropType = (DropDownList)e.Item.FindControl("dropType");
            DropDownList dropCashWithdrawType = (DropDownList)e.Item.FindControl("dropCashWithdrawType");
            if (dropType != null && hidType != null)
            {
                BindDropType(dropType, hidType.Value);
            }
            if (dropCashWithdrawType != null && hidCashWithdrawType != null)
            {
                BindDropCashWithdrawTypes(dropCashWithdrawType, hidCashWithdrawType.Value);
            }
        }
    }

    private void SetValueOfDataTable(DataSet dst)
    {
        Label lblDetailId;
        Label lblCustomerCode;
        Label lblCustomerName;
        DropDownList dropType;
        DropDownList dropCashWithdrawType;
        TextBox txtReceivingAccount;
        TextBox txtExpectedWithdrawAmount;
        TextBox txtActualWithdrawAmount;
        TextBox txtCommissionCharge;
        TextBox txtTransferDate;
        TextBox txtDescription;

        for (int i = 0; i < dlistDetail.Items.Count; i++)
        {
            lblDetailId = (Label)dlistDetail.Items[i].FindControl("lblDetailId");
            lblCustomerCode = (Label)dlistDetail.Items[i].FindControl("lblCustomerCode");
            lblCustomerName = (Label)dlistDetail.Items[i].FindControl("lblCustomerName");
            dropType = (DropDownList)dlistDetail.Items[i].FindControl("dropType");
            dropCashWithdrawType = (DropDownList)dlistDetail.Items[i].FindControl("dropCashWithdrawType");
            txtReceivingAccount = (TextBox)dlistDetail.Items[i].FindControl("txtReceivingAccount");
            txtExpectedWithdrawAmount = (TextBox)dlistDetail.Items[i].FindControl("txtExpectedWithdrawAmount");
            txtActualWithdrawAmount = (TextBox)dlistDetail.Items[i].FindControl("txtActualWithdrawAmount");
            txtCommissionCharge = (TextBox)dlistDetail.Items[i].FindControl("txtCommissionCharge");
            txtTransferDate = (TextBox)dlistDetail.Items[i].FindControl("txtTransferDate");
            txtDescription = (TextBox)dlistDetail.Items[i].FindControl("txtDescription");


            dst.Tables[0].Rows[i]["DD_ID"] = lblDetailId.Text.Trim();
            dst.Tables[0].Rows[i]["DD_CustomerID"] = lblCustomerCode.Text.Trim();
            dst.Tables[0].Rows[i]["GKMC"] = lblCustomerName.Text.Trim();
            dst.Tables[0].Rows[i]["DD_Type"] = dropType.SelectedValue;
            dst.Tables[0].Rows[i]["DD_CashWithdrawType"] = dropCashWithdrawType.SelectedValue;
            dst.Tables[0].Rows[i]["DD_ReceivingAccount"] = txtReceivingAccount.Text.Trim();
            dst.Tables[0].Rows[i]["DD_ExpectedWithdrawAmount"] = Convert.ToDecimal(txtExpectedWithdrawAmount.Text.Trim());
            dst.Tables[0].Rows[i]["DD_ActualWithdrawAmount"] = Convert.ToDecimal(txtActualWithdrawAmount.Text.Trim());
            dst.Tables[0].Rows[i]["DD_CommissionCharge"] = Convert.ToDecimal(txtCommissionCharge.Text.Trim());
            dst.Tables[0].Rows[i]["DD_TransferDate"] = txtTransferDate.Text.Trim() == "" ? DateTime.Now : Convert.ToDateTime(txtTransferDate.Text.Trim());
            dst.Tables[0].Rows[i]["DD_Description"] = txtDescription.Text.Trim();

        }

    }
}
